package util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

public class TwitterSearcher {

	public static JSONArray getTweetsByTextAndNumber(String text, int number) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("http://search.twitter.com/search.json?q=");
		
		JSONArray tweets = null;
		
		if(text != null && !text.trim().equals("")) {
			sb.append(text.replace(" ", "%20"));

			sb.append("&lang=en&result_type=recent&rpp=");

			if(number != 0) {
				sb.append(number);
			}

			StringBuffer buff = new StringBuffer();
			URL url = new URL(sb.toString());

			BufferedReader br = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));

			int c;  

	        while((c=br.read())!=-1) {  
	        	buff.append((char)c);  
	        }

	        br.close();

	        JSONObject js = new JSONObject(buff.toString());
	        tweets = js.getJSONArray("results");
		}
		
		return tweets; 
	}
}
